package com.guodi.common.utils;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

/**
 * @描述：解析文件工具类
 * @作者：彭辉
 * @时间：2019/1/8 18:03
 */
public class ReadFileUtil {

    /**
     * @描述：解析XMl地图范围
     * @作者：彭辉
     * @时间：2019/1/8 18:05
     */
    public static String loadMapextent(MultipartFile file, int size) {
        String mapextent = "";
        try {
            Document document = DocumentHelper.parseText(getAttachmentString(file, size));
            List<Element> elements = document.getRootElement().elements();
            if (elements != null && elements.size() > 0) {
                for (Element element : elements) {
                    if (element.getName().equalsIgnoreCase("XMin")) {
                        mapextent += element.getText() + ",";
                    } else if (element.getName().equalsIgnoreCase("YMin")) {
                        mapextent += element.getText() + ",";
                    } else if (element.getName().equalsIgnoreCase("XMax")) {
                        mapextent += element.getText() + ",";
                    } else if (element.getName().equalsIgnoreCase("YMax")) {
                        mapextent += element.getText() + ",";
                    }
                }
                mapextent = mapextent.substring(0, mapextent.length() - 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mapextent;
    }

    /**
     * @描述：解析XMl读取分辨率
     * @作者：彭辉
     * @时间：2019/1/8 18:04
     */
    @SuppressWarnings("unchecked")
    public static String loadResScl(MultipartFile file, int size) {
        String rtnStr = "";
        String resolution = "";
        String scale = "";
        try {
            Document document = DocumentHelper.parseText(getAttachmentString(file, size));
            List<Element> elements = document.getRootElement().elements();
            if (elements != null && elements.size() > 0) {
                for (Element element : elements) {
                    if (element.getName().equalsIgnoreCase("TileCacheInfo")) {
                        List<Element> infoElements = element.elements();
                        if (infoElements != null && infoElements.size() > 0) {
                            for (Element infoElement : infoElements) {
                                if (infoElement.getName().equalsIgnoreCase("LODInfos")) {
                                    List<Element> lodInfosElements = infoElement.elements();
                                    if (lodInfosElements != null && lodInfosElements.size() > 0) {
                                        for (Element lodInfosElement : lodInfosElements) {
                                            if (lodInfosElement.getName().equalsIgnoreCase("LODInfo")) {
                                                List<Element> lodInfoElements = lodInfosElement.elements();
                                                if (lodInfoElements != null && lodInfoElements.size() > 0) {
                                                    for (Element lodInfoElement : lodInfoElements) {
                                                        if (lodInfoElement.getName().equalsIgnoreCase("Resolution")) {
                                                            resolution += lodInfoElement.getText() + ",";
                                                        }
                                                        if (lodInfoElement.getName().equalsIgnoreCase("Scale")) {
                                                            scale += lodInfoElement.getText() + ",";
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        resolution = resolution.substring(0, resolution.length() - 1);
                                        scale = scale.substring(0, scale.length() - 1);
                                        rtnStr = resolution + "@" + scale;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rtnStr;
    }

    /**
     * @描述：读取长传配置文件，以字符串返回结果
     * @作者：彭辉
     * @时间：2019/1/8 18:04
     */
    public static String getAttachmentString(MultipartFile file, int size) {
        InputStream inStream = null;
        BufferedReader bufferedReader = null;
        String rtnString = "";
        try {
            inStream = new BufferedInputStream(file.getInputStream(), size);
            StringBuilder sb = new StringBuilder();
            bufferedReader = new BufferedReader(new InputStreamReader(inStream, "gbk"));
            String sCurrentLine = null;
            while ((sCurrentLine = bufferedReader.readLine()) != null) {
                sb.append(sCurrentLine);
            }
            rtnString = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return rtnString;
    }

    /**
     * @描述：判断请求的地址是否存在
     * @入参：url地址
     * @作者：彭辉
     * @时间：2019/1/13 12:14
     */
    public static boolean isExistHttpURLConnection(String urlString) {
        boolean isExists = true;
        HttpURLConnection urlConnection = null;
        //将中文转码
        urlString = HttpRequester.encode(RepalceDXYUrlUtil.repalceDXYUrl(urlString));
        try {
            URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");// 默认get提交模式

            urlConnection.setDoOutput(false);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            // 设置获取连接超时时间
            urlConnection.setConnectTimeout(500);
            urlConnection.setDoOutput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "500");
            InputStream in = urlConnection.getInputStream();
        } catch (IOException e) {
            isExists = false;// 链接不存在
        } catch (Exception e) {
            System.out.println("地址链接超时");
            isExists = false;// 链接不存在
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
        return isExists;
    }

    /**
     * @描述：根据URL地址获取返回的XML文件字符串
     * @作者：彭辉
     * @时间：2019/1/13 13:00
     */
    public static String getStringByUrl(String url){
        HttpRequester request = new HttpRequester();
        HttpRespons res;
        try {
            res = request.sendGet(url,null);
            String result = res.getContent();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
    * @描述: 根据URL地址获取返回的Json文件字符串
    * @作者: 代鹏刚
    * @日期: 2020/4/9 15:26
    **/
    public static String getJsonByUrl(String url){
        HttpRequester request = new HttpRequester();
        HttpRespons res;
        try {
            res = request.sendGet(url,null);
            String result = res.getContent();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @描述：根据URL地址获取返回的XML文件字符串
     * @作者：彭辉
     * @时间：2019/1/24 18:10
     */
    public static String getStringByUrl(String urlStr,Map<String,String> param){
        HttpRequester request = new HttpRequester();
        HttpRespons res;
        try {
            res = request.sendPost2(urlStr,param);
            String result = res.getContent();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析POST通过请求体传递过来的参数
     * @入参： is
     * @入参： request
     * @return
     */
    public static String pasePostInputStream(HttpServletRequest request, InputStream is){
        String post = null;
        try {
            //获取前端POST传递过来的参数信息.可以获取param=?和存放在请求体里面的流
            if (request != null && request.getParameter("param") != null) {
                post = request.getParameter("param");
                post = URLDecoder.decode(post, "UTF-8");
            } else {
                // 解析前端POST过来的数据
                byte postData[] = new byte[9999999];
                int ind = is.read();
                int i = 0;
                postData[i] = (byte) ind;
                while (ind != -1) {
                    ind = is.read();
                    if (ind != -1) {
                        i++;
                        postData[i] = (byte) ind;
                    }
                }
                byte data2[] = new byte[i + 1];
                System.arraycopy(postData, 0, data2, 0, data2.length);

                // 防止中文乱码 前端传送的时候已经编码 所以要解码
                post = URLDecoder.decode(new String(postData), "UTF-8");

                if (post.startsWith("param")) {
                    post = post.substring(post.indexOf("=") + 1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return post;
    }
}
